/*
+--------------------------------------------------------------------------
|   Mblog [#RELEASE_VERSION#]
|   ========================================
|   Copyright (c) 2014, 2019 mtons. All Rights Reserved
|   http://www.mtons.com
|
+---------------------------------------------------------------------------
*/
package com.mtons.mblog.base.storage.impl;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.mtons.mblog.base.utils.FileKit;
import com.mtons.mblog.modules.entity.GiteeFileContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 *  描述：gitee接口上传图片 <br>
 *  CreateDate: 2020/7/12 <br>
 *  @author huaguoguo
 */
@Slf4j
@Component
public class GiteeStorageImpl extends AbstractStorage {

	@Value("${gitee.access_token}")
	String giteeToken;
	@Value("${gitee.owner}")
	String owner;
	@Value("${gitee.repo}")
	String repo;

	@Override
	public void deleteFile(String storePath) {

	}

	@Override
	public String writeToStore(byte[] data, String path) throws Exception {
		String base64 = Base64Encoder.encode(data);
		// 调用gitee 新建文件api把文件上传到gitee仓库 https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}
		String urlString = new StringBuilder().append("https://gitee.com/api/v5/repos/")
				.append(owner).append("/").append(repo).append("/contents/")
				.append(path).toString();
		log.info("上传文件到gitee: {}",urlString);
		Map<String,String> body = new HashMap<>(4);
		body.put("access_token",giteeToken);
		body.put("content",base64);
		body.put("message",String.format("上传图片 %s by giteeApi",path));
		body.put("branch","master");
		// 响应数据
		String response = HttpUtil.post(urlString, JSONUtil.toJsonStr(body));
		// 解析响应数据
		String content = JSONUtil.parseObj(response).getStr("content");
		GiteeFileContent giteeFileContent = JSONUtil.toBean(content, GiteeFileContent.class);
		return giteeFileContent.getDownload_url();
	}


}
